require 'help'
require 'file_analyser'
require 'grin_generator'
require 'grin_exec'
require 'story_teller'

class Freehand

  attr_reader :filename
  attr_reader :all_help

  #``````````````````
  # constructor
  #``````````````````
  
  def initialize(storyteller, filename = nil)
    @storyteller = storyteller
    @filename = filename || "movie.swf"
    @freetext_file = in_file = FileAnalyser.rename_file_extension(@filename,".grin")
    @all_help = []
    @generator = GrinGenerator.new(@freetext_file)
    
  end
  
  #``````````````````
  # interface
  #``````````````````  

  def run
    input = nil
    while parse(input) 
      input = gets.chomp
    end
  end

  def parse(input)
    start and return true if input.nil?
    input.strip!
    finish and return false if input == "end"
    give_help and return true if input == "help"

    if (input =~ /^image/).nil?
      @generator.add input
    else
      image_url, label_text = StoryTeller.extractFileData(input)
      @storyteller.add_file_to(@generator,image_url,label_text)    
    end
    
    return true
  end

  #``````````````````
  # private methods
  #``````````````````  

  private
  
    def start
      @all_help << Help.freehand_welcome
    end

    def finish
      @all_help << Help.freehand_finish
      @generator.save
      did_compile = GrinExec.run @freetext_file, @filename, "flash"
      @all_help << Help.compile_complete(@freetext_file, @filename) if did_compile
    end
    
    def give_help
      @all_help << Help.freehand_help
    end    

end